# -*- coding:utf-8 -*-

import uuid
from pydantic import EmailStr

from fastapi import APIRouter, Depends, HTTPException, Security, Request, BackgroundTasks

from core.response import success_page, ResponsePage, ResponseModel, success
from app.logger import getLogger
from app.config import settings

from app.service.email import send_message, Email, VerifyEmailCode

from app.service import verify


logger = getLogger()

router = APIRouter(prefix="/email")

@router.post("/send", response_model=ResponseModel[Email], summary="邮件测试")
async def role_pages(email: Email, tasks: BackgroundTasks):
    tasks.add_task(send_message, email)
    return success(data=email, message="邮件发送成功")

@router.get("/code", response_model=ResponseModel[str], summary="生成验证码")
async def generate_code(request: Request, email: EmailStr):
    code = str(uuid.uuid4().int)[:4]
    await request.app.state.redis.set(f'code:{email}', code, ex=60)
    return success(data=code, message="验证码生成成功")

@router.post("/verify", response_model=ResponseModel[bool], summary="验证验证码")
async def verify_code(request: Request, email_code: VerifyEmailCode):
    redis_code = await request.app.state.redis.get(f'code:{email_code.email}')
    print(redis_code)
    if redis_code is None:
        raise HTTPException(status_code=400, detail="验证码已过期")
    if redis_code != email_code.code:
        raise HTTPException(status_code=400, detail="验证码错误")
    return success(data=True, message="验证码验证成功")



@router.post("/generate_link", response_model=ResponseModel[str], summary="生成激活链接")
async def generate_link(email: EmailStr):
    link = await verify.generate_link(email)
    # 将token存入redis
    # 发送邮件
    return success(data=link, message="激活链接生成成功")
